/*

  json_string.cpp
  Shan.Lib

 Copyright (c) 2013, Sung-Han Park
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include <istream>
#include "utf.h"
#include "json_string.h"

std::string shan::json::string::to_json() const {
	std::string ret("\"");
	char buf[7];

	for (auto it = begin() ; it != end() ; it++) {
		if (*it == '\"')
			ret.append("\\\"");
		else if (*it == '\\')
			ret.append("\\\\");
		else if (*it == '\b')
			ret.append("\\b");
		else if (*it == '\f')
			ret.append("\\f");
		else if (*it == '\n')
			ret.append("\\n");
		else if (*it == '\r')
			ret.append("\\r");
		else if (*it == '\t')
			ret.append("\\t");
		else if ((*it >= 0x00) && (*it <= 0x1f)) {
			std::sprintf(buf, "\\u%04x", *it);
			ret.append(buf);
		}
		else { // unescaped
			ret.push_back(*it);
		}
	}

	ret.push_back('"');
	return ret;
}

void shan::json::string::internal_parse(std::istream& is) {
	if (is.eof() || (is.peek() != '"'))
		throw json::exception("Invalid syntax was found.");
	is.get(); // skip '"'

	int inx;
	char16_t code1, code2;
	char hexdigits[5];
	while (!is.eof()) {
		switch (is.peek()) {
			case '\\':
				is.get(); // skip backslash
				switch (is.peek()) {
					case '"':
					case '\\':
					case '/':
						push_back(is.get());
						break;
					case 'b':
						is.get();
						push_back('\b');
						break;
					case 'f':
						is.get();
						push_back('\f');
						break;
					case 'n':
						is.get();
						push_back('\n');
						break;
					case 'r':
						is.get();
						push_back('\r');
						break;
					case 't':
						is.get();
						push_back('\t');
						break;
					case 'u':
						is.get();
						for (inx = 0 ; inx < 4 ; inx++) {
							if (std::isxdigit(is.peek()))
								hexdigits[inx] = is.get();
							else
								throw json::exception("Invalid syntax was found. 4 hex digits sequence was not found after '\\u'.");
						}
						hexdigits[4] = '\0';
						code1 = static_cast<int>(std::strtol(hexdigits, nullptr, 16));
						if (shan::utf::is_lead_surrogate(code1)) {
							if (is.peek() == '\\') {
								is.get();
								if (is.peek() == 'u') {
									is.get();
									for (inx = 0 ; inx < 4 ; inx++) {
										if (std::isxdigit(is.peek()))
											hexdigits[inx] = is.get();
										else
											throw json::exception("Invalid syntax was found. 4 hex digits sequence was not found after '\\u'.");
									}
									hexdigits[4] = '\0';
									code2 = static_cast<int>(std::strtol(hexdigits, nullptr, 16));

									if (shan::utf::is_trail_surrogate(code2))
										append(shan::utf::to_utf8(shan::utf::surrogate_pair_to_utf32(code1, code2)));
									else
										throw json::exception("Invalid syntax was found. UTF16 lead surrogate was found but trail surrogate was not.");
								}
								else {
									throw json::exception("Invalid syntax was found. UTF16 lead surrogate was found but trail surrogate was not.");
								}
							}
							else {
								throw json::exception("Invalid syntax was found. UTF16 lead surrogate was found but trail surrogate was not.");
							}
						}
						else {
							append(shan::utf::to_utf8(code1));
						}
						break;
				}
				break;

			case '\"': // end of string
				is.get();
				return;

			default:
				push_back(is.get());
				break;
		}
	}

	throw json::exception("Invalid syntax was found. json::string was unterminated.");
}
